package com.xbq.exceleditor.ui

import android.net.Uri
import android.os.Bundle
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import cn.jzvd.Jzvd
import com.blankj.utilcode.util.ActivityUtils
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.ToastUtils
import com.bumptech.glide.Glide
import com.gyf.immersionbar.ktx.immersionBar
import com.xbq.exceleditor.OFFICE_TYPE
import com.xbq.exceleditor.R
import com.xbq.exceleditor.adapter.CollectionPlayListAdapter
import com.xbq.exceleditor.adapter.RecommendVideoAdapter
import com.xbq.exceleditor.databinding.ActivityPlayVideoBinding
import com.xbq.exceleditor.utils.ensureVip
import com.xbq.xbqsdk.component.activity.VBActivity
import com.xbq.xbqsdk.component.recyleview.GridSpaceDecoration
import com.xbq.xbqsdk.component.recyleview.LinearSpaceDecoration
import com.xbq.xbqsdk.core.event.UserInfoChanged
import com.xbq.xbqsdk.net.officeeditor.OfficeEditorApi
import com.xbq.xbqsdk.net.officeeditor.dto.CollectionVideosDto
import com.xbq.xbqsdk.net.officeeditor.dto.RelatedRecommendVideosDto
import com.xbq.xbqsdk.net.officeeditor.vo.OfficeVideo
import com.xbq.xbqsdk.net.officeeditor.vo.OfficeVideoCollection
import com.xbq.xbqsdk.util.click.onDebouncedClick
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.launch
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import javax.inject.Inject


/**
 * Author: liaohaiping
 * Time: 2020-10-30
 * Description:
 */
@AndroidEntryPoint
class PlayVideoActivity :
    VBActivity<ActivityPlayVideoBinding>() {
    companion object {
        fun start(video: OfficeVideo) {
            var extras = Bundle().apply {
                putParcelable("video", video)
            }
            ActivityUtils.startActivity(extras, PlayVideoActivity::class.java)
        }

        fun start(videoCollection: OfficeVideoCollection) {
            var extras = Bundle().apply {
                putParcelable("videoCollection", videoCollection)
            }
            ActivityUtils.startActivity(extras, PlayVideoActivity::class.java)
        }
    }

    @Inject
    lateinit var officeEditorApi: OfficeEditorApi
    var beginVideo: OfficeVideo? = null
    var beginVideoCollection: OfficeVideoCollection? = null
    @Inject
    lateinit var playListAdapter: CollectionPlayListAdapter
    @Inject
    lateinit var recommendVideoAdapter: RecommendVideoAdapter

    override fun useEventBus(): Boolean {
        return true
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onUserInfoChanged(event: UserInfoChanged) {
        playListAdapter.refreshNeedPay()
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding.adview.init("playvideo",this)
        immersionBar {
            fitsSystemWindows(true,R.color.bg)
            statusBarDarkFont(true)
        }
        beginVideo = intent.getParcelableExtra("video") as OfficeVideo?
        beginVideoCollection =
            intent.getParcelableExtra("videoCollection") as OfficeVideoCollection?

        binding.btnBack.onDebouncedClick { finish() }
        initRecyclerView()
        if (beginVideo != null) {
            initByVideo(beginVideo!!)
        } else if (beginVideoCollection != null) {
            loadCollectionsVideos(beginVideoCollection!!.id)
        }
    }


    private fun initByVideo(video: OfficeVideo) {
        setupVideoInfo(video)
        loadCollectionsVideos(video.collectionId)
        loadRecommendVideos(video)
        binding.tvTitle.text = video.title
    }

    private fun setupVideoInfo(video: OfficeVideo) {
        binding.jzVideo.let {
            it.setUp(video.url, video.title)
            Glide.with(this)
                .load(Uri.parse(video.thumbnail))
                .into(it.posterImageView)
            it.startVideoAfterPreloading()
            playListAdapter.select(video)
            binding.tvTitle.text = video.title
        }
    }

    private fun initRecyclerView() {
        binding.playList.let {
            it.adapter = playListAdapter
            it.layoutManager = LinearLayoutManager(this, RecyclerView.HORIZONTAL, false)
            it.addItemDecoration(LinearSpaceDecoration(8f, orientation = RecyclerView.HORIZONTAL))
            playListAdapter.setOnItemClickListener { ad, view, position ->
                val item = playListAdapter.getItem(position)
                ensureVip("playVideo", item.isNeedVip) { setupVideoInfo(item) }

            }
        }

        binding.recommendVideoList.let {
            it.adapter = recommendVideoAdapter
            it.layoutManager = GridLayoutManager(this, 2)
            it.addItemDecoration(GridSpaceDecoration(2,8f))
            recommendVideoAdapter.setOnItemClickListener { ad, view, position ->
                val item = recommendVideoAdapter.getItem(position)
                ensureVip("playRecommondVideo", item.isNeedVip) {
                    initByVideo(item)
                }
            }
        }
    }

    private fun loadCollectionsVideos(videoCollectionId: Long) {
        lifecycleScope.launch {
            val res =
                officeEditorApi.collection_videos(CollectionVideosDto(videoCollectionId))
            if (res.success()) {
                playListAdapter.setList(res.data!!)
                if (beginVideo == null) {
                    beginVideo = res.data!!.first()
                    setupVideoInfo(beginVideo!!)
                    loadRecommendVideos(beginVideo!!)
                }
                val selectedIndex = playListAdapter.selectedIndex()
                if (selectedIndex != -1) {
                    binding.playList.scrollToPosition(selectedIndex)
                } else {
                    LogUtils.d("selected index is -1")
                }
            } else {
                ToastUtils.showShort(res.message)
            }
        }
    }

    private fun loadRecommendVideos(video: OfficeVideo) {
        lifecycleScope.launch {
            val res =
                officeEditorApi.related_recommend_videos(
                    RelatedRecommendVideosDto(
                        OFFICE_TYPE,
                        video.id,
                        6
                    )
                )
            if (res.success()) {
                recommendVideoAdapter.setList(res.data!!)
            } else {
                ToastUtils.showShort(res.message)
            }
        }
    }

    override fun onBackPressed() {
        if (Jzvd.backPress()) {
            return
        }
        super.onBackPressed()
    }

    override fun onPause() {
        super.onPause()
        Jzvd.releaseAllVideos()
    }
}